package main

import (
	"bytes"
	log "github.com/sirupsen/logrus"
	"os"
	"os/exec"
	"strconv"
	"text/template"
)

type Demo struct {
	SettleDetailCount int32
	CoinCount         float64 //int64 float64 会存在1e+11，int64 不存在这个问题
	CoinCountStr      string
}

func main() {
	htmlTmp := "jmsd-1234.html"
	demo := Demo{
		SettleDetailCount: 10000000,
		CoinCount:         1000.06,
	}
	demo.CoinCountStr = strconv.FormatFloat(demo.CoinCount, 'f', 2, 64)
	defer func() {
		// 删除html中间文件
		if err := os.Remove(htmlTmp); err != nil {
			log.Errorf("出错了", err.Error())
		}
	}()

	// 解析指定文件生成模板对象
	tpl := template.Must(template.ParseFiles("./html/tpl.html"))
	err := func() error {
		f, err := os.Create(htmlTmp)
		if err != nil {
			return err
		}
		defer f.Close()

		if err := tpl.Execute(f, demo); err != nil {
			return err
		}
		return nil
	}()
	if err != nil {
		log.Errorf("出错了", err.Error())
		return
	}

	// 判断html文件是否合法
	f, err := os.Stat(htmlTmp)
	if err != nil {
		log.Errorf("出错了", err.Error())
		return
	}
	if f.Size() == 0 {
		log.Errorf("出错了")
		return
	}
	os.Setenv("PATH", "/usr/local/mysql/bin:/usr/local/maven/apache-maven-3.8.2/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/bin")
	// html转pdf
	cmd := exec.Command("/bin/bash", "-c", " wkhtmltopdf "+htmlTmp+" ./test5678.pdf")
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	if err := cmd.Start(); err != nil {
		log.Errorf("导出 pdf 出错了", err.Error())
		return
	}
	if err := cmd.Wait(); err != nil {
		log.Errorf(err.Error(), stderr.String())
		return
	}
	log.Info("-----执行完毕------")
}
